﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Reflection;
using System.Text;

namespace Common.ExtensionMethods
{
    /// <summary>
    /// 枚举的扩展方法
    /// </summary>
    /// <remarks>create by chenjinjian.com on 2015-01-14</remarks>
    public static class EnumExtension
    {
        /// <summary>
        /// 获取枚举的Key(文本)其实就是ToString()
        /// </summary>
        /// <param name="e"></param>
        /// <remarks>create by chenjinjian.com on 2015-01-14</remarks>
        /// <returns></returns>
        public static string GetKey(this Enum e)
        {
            return e.ToString();
        }
        /// <summary>
        /// 获取枚举的值
        /// </summary>
        /// <param name="e"></param>
        /// <remarks>create by chenjinjian.com on 2015-01-14</remarks>
        /// <returns>枚举对应的值</returns>
        public static int GetValue(this Enum e)
        {
            if (e == null)
            {
                return 0;
            }
            return Convert.ToInt32(e);
        }

        /// <summary>
        /// 获取枚举描述信息
        /// </summary>
        /// <param name="en">枚举</param>
        /// <remarks>create by chenjinjian.com on 2015-01-16</remarks>
        /// <returns></returns>
        public static string GetDescription(this Enum e)
        {
            Type type = e.GetType();
            MemberInfo[] memInfo = type.GetMember(e.ToString());
            if (memInfo.Length > 0)
            {
                object[] attrs = memInfo[0].GetCustomAttributes(typeof(DescriptionAttribute), false);
                if (attrs.Length > 0)
                    return ((DescriptionAttribute)attrs[0]).Description;
            }
            return e.ToString();
        }

    }
}
